package com.ibsol.control
{
	import com.ibsol.model.City;
	import com.ibsol.model.Weather;
	import com.ibsol.service.CityService;
	import com.yahoo.webapis.weather.WeatherService;
	
	import flash.xml.XMLNode;
	
	import mx.collections.ArrayCollection;
	import mx.managers.CursorManager;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	public class WeatherDelegate{
		
		//yahoo weather api
		private var ws:com.yahoo.webapis.weather.WeatherService;
		//private var df:DateFormatter;
		private var cityService:CityService;
		private var weatherService:com.ibsol.service.WeatherService;
		//定义月的数字星期的数字
		private static var moonArr:Object={"Jan.":"1","Feb.":"2","Mar.":3,"Apr.":"4","May":"5","Jun":"6","Jul":"7","Aug.":"8","Sept.":"9","Oct.":"10","Nov.":"11","Dec.":"12"};
		private static var weekArr:Object={"Mon.":"1","Tue.":"2","Wed.":"3","Thu.":"4","Fri.":"5","Sat.":"6","Sun.":"7"};
		//The max serial id's citycode
		private var maxSerialID:String = "";
		public function WeatherDelegate(){
			ws=new com.yahoo.webapis.weather.WeatherService();
			//df=new DateFormatter();
			//df.formatString="YYYY-MM-DD";
			cityService = new CityService();
			weatherService = new com.ibsol.service.WeatherService;
		}
		/**
		 * 更新城市集合中的天气情况，用yahoo weather服务
		 **/
		/* public function updateCityWeather(cityCodeArr:ArrayCollection):void{
		 	
		 	ws.addEventListener(WeatherResultEvent.WEATHER_LOADED,function (e:WeatherResultEvent):void{
		 		var yw:com.yahoo.webapis.weather.Weather=e.data as com.yahoo.webapis.weather.Weather;
		 		
		 		
		 		//得到城市信息
		 		var local:Location=yw.location;
		 		//按城市名称得到本地城市的信息对象
		 		var city:City=cityService.getCityByName(local.city);
		 		//按城市编号得到原有的天气情况
		 		var weather:Weather=weatherService.getWeatherByCityId(city.id);
		 		if(weather==null){
		 			weather=new Weather();
		 			weather.cityid=city.id;
		 		}
		 		//得到weather服务的该城市更新时间
		 		var updateDate:Date=yw.date;
		 		
		 		trace("UTC时间"+(updateDate.hoursUTC)+":"+updateDate.minutesUTC);
		 		
		 		//得到当前信息
		 		var currentConditions:CurrentConditions=yw.current;
		 		
		 		//var locale:Locale=ResourceManager.getInstance().localeChain;
		 		//if(locale.country==city.country){
		 			//trace();
		 		//}
		 		
		 		//得到该城市的天文信息，日升时间日落时间
		 		var astromony:Astronomy=currentConditions.astronomy;
		 		var upDate:Date=astromony.sunrise;
		 		trace("日升时间"+(upDate.hoursUTC)+":"+upDate.minutesUTC);
		 		var downDate:Date=astromony.sunset;
		 		trace("日落时间"+(downDate.hoursUTC)+":"+downDate.minutesUTC);
		 		//设置图片是白天还是夜晚的
		 		var picnd:String="d";
		 		//当地时间小时数加1是真正的小时
		 		if((updateDate.hoursUTC>downDate.hoursUTC)||(updateDate.hoursUTC<upDate.hoursUTC)){
		 			picnd="n";
		 		}else if(updateDate.hoursUTC==downDate.hoursUTC){
		 			if(updateDate.minutesUTC>downDate.minutesUTC){
		 				picnd="n";
		 			}
		 		}else if(updateDate.hoursUTC==upDate.hoursUTC){
		 			if(updateDate.minutesUTC<upDate.minutesUTC){
		 				picnd="n";
		 			}
		 		}
		 		//设置描述信息
		 		weather.des=currentConditions.description;
		 		//设置图片编号
		 		var imgURL:String=currentConditions.imageURL;
		 		var point:int=imgURL.lastIndexOf(".");
		 		var xhx:int=imgURL.lastIndexOf("/");
		 		var imgurl:String=imgURL.substring(xhx+1,point);
		 		
		 		weather.pictureid=imgurl+picnd;
		 		//设置当前天气
		 		weather.celcius=currentConditions.temperature.toString();
		 		//得到大气信息
		 		var atmosphere:Atmosphere=currentConditions.atmosphere;
		 		//设置湿度
		 		weather.humidity=atmosphere.humidity.toString();
		 		//设置可见度
		 		weather.visibility=atmosphere.visibility.toString();
		 		//得到当天的天气信息(最高最低温度)
		 		var forecastConditions:ForecastConditions=ForecastConditions(yw.forecast[0]);
		 		
		 		weather.high=forecastConditions.high.toString();
		 		weather.low=forecastConditions.low.toString();
		 		//设置更新时间
		 		//var currentDay:Date=forecastConditions.date;
		 		//weather.updateTime=df.format(currentDay);
		 		weather.updateTime=df.format(new Date());
		 		//设置明天预报
		 		var forecast:String="<tomorrow><date>";
		 		forecastConditions=ForecastConditions(yw.forecast[1]);
		 		forecast+=df.format(forecastConditions.date.toDateString())+"</date><description>";
		 		forecast+=forecastConditions.description+"</description><high>";
		 		forecast+=forecastConditions.high.toString()+"</high><imageURL>"
		 		imgURL=forecastConditions.imageURL;
		 		point=imgURL.lastIndexOf(".");
		 		xhx=imgURL.lastIndexOf("/");
		 		imgurl=imgURL.substring(xhx+1,point);
		 		//默认是白天
		 		forecast+=imgurl+"d</imageURL><low>";
		 		forecast+=forecastConditions.low.toString()+"</low></tomorrow>";
		 		var xml:XML=new XML(forecast);
		 		weather.forecast=xml.toXMLString();
		 		if(weather.id==-1)
		 			weatherService.insertWeather(weather);
		 		else
		 			weatherService.updateWeatherById(weather);
		 	});
		 	ws.addEventListener(WeatherErrorEvent.INVALID_LOCATION,function (e:WeatherErrorEvent):void{
		 		trace("城市的城市码无效");
		 	});
		 	for(var i:int=0;i<cityCodeArr.length;i++){
		 		var cc:String=cityCodeArr.getItemAt(i) as String;
		 		//得到城市的天气情况 c代表摄氏度
		 		ws.getWeather(cc,"c");
		 	}
		 }*/
		 
		 
		 public function updateWeatherXML(cityCodeArr:ArrayCollection):void{
		 	var weatherHttp:HTTPService=new HTTPService();
		 	this.maxSerialID = cityCodeArr.getItemAt(cityCodeArr.length - 1).toString();
		 	for(var i:int=0;i<cityCodeArr.length;i++){
		 		if(i == 0)
		 			CursorManager.setBusyCursor();
		 		if(cityCodeArr.getItemAt(i) == "")
		 			continue;
		 		weatherHttp.url="http://xml.weather.yahoo.com/forecastrss?u=c&p="+cityCodeArr.getItemAt(i);
		 		weatherHttp.method="GET";
		 		weatherHttp.contentType="text/xml";
		 		weatherHttp.useProxy=false;
		 		weatherHttp.resultFormat="xml";
		 		weatherHttp.addEventListener(ResultEvent.RESULT,resultHandler);
		 		weatherHttp.addEventListener(FaultEvent.FAULT,faultHandler);
		 		weatherHttp.send();
		 	}
		 }
		 private function faultHandler(e:FaultEvent):void{
		 	trace("更新天气出错"+e.fault.message);
		 	CursorManager.removeBusyCursor();
		 }
		 private function resultHandler(e:ResultEvent):void{
		 	var result:XMLNode=e.result as XMLNode;
		 	//得到channel节点
		 	var channelNode:XMLNode=result.firstChild;
		 	//得到channel节点下的title节点
		 	var titleNode:XMLNode=channelNode.firstChild;
		 	
		 	
		 	//得到城市信息/ 名称,如果是ERROR的话，表示查询失败
		 	var cityName:String=getCityName(titleNode.firstChild.nodeValue);
		 	if(cityName!="Error"){
		 		//trace(result);
		 		trace("城市编号："+cityName);
		 		//按城市名称得到本地城市的信息对象
		 		var city:City=cityService.getCityByName(cityName);
		 		//按城市编号得到原有的天气情况
		 		var weather:Weather=weatherService.getWeatherByCityId(city.id);
		 		if(weather==null){
		 			weather=new Weather();
		 			weather.cityid=city.id;
		 		}
		 		//得到weatherService中该城市的天气更新时间
		 		var lastBuildDate:XMLNode=titleNode.nextSibling.nextSibling.nextSibling.nextSibling;
		 		var currentTime:String=getTime(lastBuildDate.firstChild.nodeValue);
		 		trace("更新时间："+currentTime);
		 		weather.updateTime=currentTime;
		 		//得到atmosphere大气信息，包括适度和可见度 atmosphere节点
		 		var atmosphereNode:XMLNode=lastBuildDate.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;
		 		var humidity:String=getAttributeByXMLNode(atmosphereNode,"humidity");
		 		var visibility:String=getAttributeByXMLNode(atmosphereNode,"visibility");
		 		trace("湿度："+humidity+"%");
		 		trace("可见度："+parseInt((parseFloat(visibility)*100).toString())+"mi");
		 		weather.humidity=humidity;
		 		weather.visibility=(parseFloat(visibility)*100).toString();
		 		
		 		//得到气象信息，包括日升日落的时间 astromony节点,并设置图片后缀
		 		var astromonyNode:XMLNode=atmosphereNode.nextSibling;
		 		var sunrise:String=getAttributeByXMLNode(astromonyNode,"sunrise");
		 		var sunset:String=getAttributeByXMLNode(astromonyNode,"sunset");
		 		var picDN:String=getPicDN(currentTime,sunrise,sunset);
		 		//trace(picDN);
		 		//得到具体天气情况和图片  item节点
		 		var itemNode:XMLNode=astromonyNode.nextSibling.nextSibling;
		 		//得到condition 节点
		 		var conditionNode:XMLNode=itemNode.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;
		 		var picid:String=getAttributeByXMLNode(conditionNode,"code")+picDN;
		 		trace("图片编号："+picid);
		 		weather.pictureid=picid;
		 		var celcius:String=getAttributeByXMLNode(conditionNode,"temp");
		 		trace("当前温度："+celcius);
		 		weather.celcius=celcius;
		 		var des:String=getAttributeByXMLNode(conditionNode,"text");
		 		trace("描述："+des);
		 		weather.des=des;
		 		//最高温度最低温度，明天温度详细情况xml
		 		//得到当天的forecast节点
		 		var curforecastNode:XMLNode=conditionNode.nextSibling.nextSibling;
		 		var high:String=getAttributeByXMLNode(curforecastNode,"high");
		 		var low:String=getAttributeByXMLNode(curforecastNode,"low");
		 		trace("high:"+high+"low:"+low);
		 		weather.low=low;
		 		weather.high=high;
		 		//得到明天的forecast节点
		 		var forecastStr:String="<weather>";
		 		var tempNode:XMLNode=curforecastNode.nextSibling;
		 		//循环得到所有天数的气象信息
		 		if(tempNode!=null){
		 			while(tempNode.prefix=="yweather"&&tempNode.localName=="forecast"){
		 				forecastStr+="<yw>";
		 				var day:String=getAttributeByXMLNode(tempNode,"day");
		 				var date:String=getAttributeByXMLNode(tempNode,"date");
		 				var ylow:String=getAttributeByXMLNode(tempNode,"low");
		 				var yhigh:String=getAttributeByXMLNode(tempNode,"high");
		 				var text:String=getAttributeByXMLNode(tempNode,"text");
		 				var code:String=getAttributeByXMLNode(tempNode,"code");
		 				forecastStr+="<day>"+day+"</day><date>"+date+"</date><low>"+ylow+"</low><high>"+yhigh+"</high><text>"+text+"</text><code>"+code+"d"+"</code>";
		 				forecastStr+="</yw>";
		 				tempNode=tempNode.nextSibling;
		 				if(tempNode==null)
		 					break;
		 			}
		 		}
		 		forecastStr+="</weather>";
		 		trace(forecastStr);
		 		var tempXml:XML=new XML(forecastStr);
		 		weather.forecast=tempXml.toXMLString();
		 		//判断是新建的还是已经存在要修改的
		 		if(weather.id==-1)
		 			weatherService.insertWeather(weather);
		 		else
		 			weatherService.updateWeatherById(weather);
		 		//Remove the busy cursor
		 		if(city.cityCode == this.maxSerialID)
		 			CursorManager.removeBusyCursor();
		 	}
		 }
		 /*得到城市名称，通过title标签的值*/
		 private function getCityName(str:String):String{
		 	var lineSymbolI:int=str.indexOf("-");
		 	var douSymbolI:int=str.indexOf(",");
		 	if(douSymbolI==-1)//表示没有找到
		 		douSymbolI=str.length;
		 	return str.substring(lineSymbolI+2,douSymbolI);
		 }
		 /*得到时间,通过lastBuildDate标签的值*/
		 private function getTime(str:String):String{
		 	var temparr:Array=str.split(" ");
		 	var index:int=-1;
		 	for(var i:int=0;i<temparr.length;i++){
		 		if(temparr[i]=="am"||temparr[i]=="pm"){
		 			index=i;
		 			break;
		 		}
		 	}
		 	return temparr[index-1]+" "+temparr[index];
		 }
		 /*得到节点的属性值*/
		 private function getAttributeByXMLNode(xn:XMLNode,attribute:String):String{
		 	return xn.attributes[attribute];
		 }
		 /*得到时间的小时数和分钟数*/
		 private function getTimeHM(Time:String):Array{
		 	var temparr:Array=Time.split(" ");
		 	var ctH:int=0;
		 	var ctM:int=0;
		 	var arr:Array=temparr[0].toString().split(":");
		 	if(temparr[1]=="pm"){
		 		ctH=parseInt(arr[0])+12;
		 		ctM=parseInt(arr[1]);
		 	}else{
		 		ctH=parseInt(arr[0]);
		 		ctM=parseInt(arr[1]);
		 	}
		 	var ar:Array=new Array();
		 	ar.push(ctH);
		 	ar.push(ctM);
		 	return ar;
		 }
		 private function getPicDN(currentTime:String,sunrise:String,sunset:String):String{
		 	var picDN:String="d";
		 	var currentarr:Array=getTimeHM(currentTime);
		 	var risearr:Array=getTimeHM(sunrise);
		 	var setarr:Array=getTimeHM(sunset);
		 	if((parseInt(currentarr[0].toString())<parseInt(risearr[0].toString()))||(parseInt(currentarr[0].toString())>parseInt(setarr[0].toString()))){
		 		picDN="n";
		 	}else if(parseInt(currentarr[0].toString())==parseInt(risearr[0].toString())){
		 		if(parseInt(currentarr[1].toString())<parseInt(risearr[1].toString())){
		 			picDN="n";
		 		}
		 	}else if(parseInt(currentarr[0].toString())==parseInt(setarr[0].toString())){
		 		if(parseInt(currentarr[1].toString())>parseInt(setarr[1].toString())){
		 			picDN="n";
		 		}
		 	}
		 	return picDN;
		 }
		 //得到时间的当地信息化（本地化的时间信息）
	}
}